<script setup lang="ts">
import axios from 'axios'
import { ref } from 'vue'
import { timeFormat } from '@/hooks/util'
import * as accountApi from '@/api/account'
import { message } from 'ant-design-vue'
import GroupList from './components/GroupList.vue'
import EditRemark from './components/EditRemark.vue'
import DelWxRobot from './components/DelWxRobot.vue'
import SetGroup from './components/SetGroup.vue'
import RechargeAuthorization from './components/RechargeAuthorization.vue'
import Authorization from './components/Authorization.vue'
import IMAuthorization from './components/IMAuthorization.vue'
import DiolagBox from '../../components/Modal/index.vue'
import TransferDuration from './components/TransferDuration.vue'
import SearchDrawer from '@/components/search-drawer/Index.vue'

const searchDrawerRef = ref()
const groupListRef = ref()
const editRemarkRef = ref()
const delWxRobotRef = ref()
const setGroupRef = ref()
const rechargeAuthorizationRef = ref()
const authorizationRef = ref()
const IMAuthorizationRef = ref()
const TransferDurationRef = ref()

let searchFlag = ref<boolean>(false)

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}
const handlePageChange = (page: any, pageSize: any) => {
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}
const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true,
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  wechatId?: string | undefined
  nickName?: string | undefined
  remark?: string | undefined
  groupId?: string
  expireState?: string | number
  robotState?: string | number
  updateState?: string | number
  fishState?: string | number
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  {
    title: '头像',
    key: 'avatar',
    width: 100,
    algin: 'center',
  },
  {
    title: '昵称/分组',
    key: 'xyAccount',
    width: 300,
  },
  {
    title: '鱼小铺等级/会员名',
    key: 'userName',
    width: 350,
  },
  {
    title: '闲鱼/客户端状态',
    key: 'fishState',
    width: 300,
  },
  {
    title: '备注/编号',
    key: 'groupId',
    width: 350,
  },
  {
    title: '评价分/好评率',
    key: 'shopLevel',
    width: 220,
  },

  {
    title: '闲鱼授权状态/续费状态',
    key: 'xyAuthorization',
    width: 350,
  },
  {
    title: '创建/过期时间',
    key: 'createTime',
    width: 300,
  },
  {
    key: 'action',
    width: 150,
    fixed: 'right',
  },
]
// 表格多选
const selectedRowKey = ref<Array<any>>([])
const selectedRow = ref<Array<object>>([])
const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
  selectedRowKey.value = selectedRowKeys
  selectedRow.value = selectedRows
}

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize

  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

const EditRemarkSet = async (record: any) => {
  record.isRemarkShow = true
}
const getList = async () => {
  loading.value = true
  try {
    let { state, data, message: msg } = await accountApi.getFishRobotList(searchParams.value)
    if (state === 200) {
      data.list.forEach((item: { isRemarkShow: boolean }) => {
        item.isRemarkShow = false
      })
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}
// 状态数量统计 - 闲鱼
interface XyNumInfo {
  fishRobotOffLineNum: number | string
  fishRobotOnLineNum: number | string
  renewNum: number | string
  robotOffLineNum: number | string
  robotOnLineNum: number | string
  totality: number | string
  updateNum: number | string
}
const xyNumInfo = ref<XyNumInfo>()
// 获取闲鱼 状态
const getXyStatusNum = async () => {
  try {
    let { state, data, message: msg } = await accountApi.fishStatisticalMagnitude()
    if (state === 200) {
      xyNumInfo.value = data
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

onMounted(() => {
  // 分组之后再加载列表，不然会出现bug
  getGroupList()
  getXyStatusNum()
})

// 查询
const formRef = ref()
import type { SelectProps } from 'ant-design-vue'
const robotStateList = ref<SelectProps['options']>([
  {
    label: '正常',
    value: 1,
  },
  {
    label: '手动关闭',
    value: 0,
  },
  {
    label: '异常',
    value: -1,
  },
])

const expireStateList = ref<SelectProps['options']>([
  {
    label: '无需续费',
    value: 0,
  },
  {
    label: '需要续费',
    value: 1,
  },
])

const updateStateList = ref<SelectProps['options']>([
  {
    label: '无需更新',
    value: 0,
  },
  {
    label: '需要更新',
    value: 1,
  },
])

const wechatStateList = ref<SelectProps['options']>([
  {
    label: '离线',
    value: 0,
  },
  {
    label: '在线',
    value: 1,
  },
])

const groupList = ref<SelectProps['options']>([])
const getGroupList = async () => {
  try {
    let { state, data, message: msg } = await accountApi.getFishRobotGroupList()
    if (state === 200) {
      groupList.value = data
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}
interface FormState {
  wechatId?: string | undefined
  nickName?: string | undefined
  remark?: string | undefined
  groupId?: string | undefined
  expireState?: string | number
  robotState?: string | number
  updateState?: string | number
  fishState?: string | number
}
const formState = reactive<FormState>({})
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    searchParams.value.wechatId = formState.wechatId || ''
    searchParams.value.nickName = formState.nickName || ''
    searchParams.value.remark = formState.remark || ''
    searchParams.value.groupId = formState.groupId || ''
    searchParams.value.expireState = formState.expireState
    searchParams.value.robotState = formState.robotState
    searchParams.value.updateState = formState.updateState
    searchParams.value.fishState = formState.fishState
    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1

  formRef.value.resetFields()
  Reflect.deleteProperty(searchParams.value, 'wechatId')
  Reflect.deleteProperty(searchParams.value, 'nickName')
  Reflect.deleteProperty(searchParams.value, 'remark')
  Reflect.deleteProperty(searchParams.value, 'groupId')
  Reflect.deleteProperty(searchParams.value, 'expireState')
  Reflect.deleteProperty(searchParams.value, 'robotState')
  Reflect.deleteProperty(searchParams.value, 'updateState')
  Reflect.deleteProperty(searchParams.value, 'fishState')

  getList()
}

const advancedSearch = () => {
  searchDrawerRef.value.showDrawer()
}

const showGroupName = (id: string) => {
  return groupList.value?.find(item => item.id === id)?.groupName || '未分组'
}

// 授权状态
const getAuthoration = (time: string) => {
  // 获取当前时间戳（毫秒）
  const currentTime = Date.now()
  if (Number(time) === 0) {
    return -1 // '未授权'
  } else if (Number(time) > currentTime) {
    return 1 // '已授权'
  } else {
    return -2 //'授权过期'
  }
}

// 分组管理
const showGroupList = () => {
  groupListRef.value.showModal('LdleFish')
}

const addGroup = async () => {
  setGroupRef.value.showModal(selectedRowKey.value, 'LdleFish')
}

// 备注
const handleRemark = async (id: string, remark: string) => {
  let params = { id, remark }
  try {
    const { state, message: msg } = await accountApi.editFishRobotRemark(params)
    if (state === 200) {
      message.success('备注保存成功')
      getList()
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 充值时长
const rechargeAuthorization = (id: string) => {
  rechargeAuthorizationRef.value.showModal(id, 'xy')
}

// 授权
const authorization = async (id: string) => {
  try {
    let { state, message: msg, data } = await accountApi.auth()
    if (state === 200) {
      window.open(data.redirectUrl)
      authorizationRef.value.showModal(data.taskId)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// IM授权
const showIMAuthorization = () => {
  IMAuthorizationRef.value.showModal()
}

const DiolagBoxRef = ref()
const addAccount = () => {
  DiolagBoxRef.value.setVisible(true)
}

// 转移时长
const transferDuration = (id: string) => {
  TransferDurationRef.value.showModal('xy', id)
}
</script>

<template>
  <DiolagBox ref="DiolagBoxRef" :width="700" :height="700">
    <template #contentValue>
      <a-image
        style="width: 100%; height: 100%"
        src="http://xc-ticket-img.liangpiao.net.cn/ticketImg/account.png"
      />
    </template>
  </DiolagBox>
  <div>
    <div class="searchBox">
      <a-form ref="formRef" layout="inline" :model="formState" class="formClass">
        <a-form-item label="分组查询" name="groupId">
          <a-select
            v-model:value="formState.groupId"
            placeholder="请选择"
            allowClear
            style="width: 200px"
          >
            <a-select-option v-for="(item, index) in groupList" :key="index" :value="item.id">
              {{ item.groupName }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="闲鱼昵称" name="nickName">
          <a-input v-model:value="formState.nickName" placeholder="闲鱼昵称" style="width: 200px" />
        </a-form-item>

        <a-form-item label="软件状态" name="robotState">
          <a-select
            v-model:value="formState.robotState"
            placeholder="请选择"
            allowClear
            style="width: 200px"
          >
            <a-select-option
              v-for="(item, index) in robotStateList"
              :key="index"
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <SearchDrawer ref="searchDrawerRef">
          <div>
            <a-form-item label="分组查询" name="groupId">
              <a-select
                v-model:value="formState.groupId"
                placeholder="请选择"
                allowClear
                style="width: 250px"
              >
                <a-select-option v-for="(item, index) in groupList" :key="index" :value="item.id">
                  {{ item.groupName }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="闲鱼昵称" name="nickName">
              <a-input
                style="width: 250px"
                v-model:value="formState.nickName"
                placeholder="闲鱼昵称"
              />
            </a-form-item>

            <a-form-item label="续费状态" name="expireState">
              <a-select
                v-model:value="formState.expireState"
                placeholder="请选择"
                allowClear
                style="width: 250px"
              >
                <a-select-option
                  v-for="(item, index) in expireStateList"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="软件状态" name="robotState">
              <a-select
                v-model:value="formState.robotState"
                placeholder="请选择"
                allowClear
                style="width: 250px"
              >
                <a-select-option
                  v-for="(item, index) in robotStateList"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="软件更新" name="updateState">
              <a-select
                v-model:value="formState.updateState"
                placeholder="请选择"
                allowClear
                style="width: 250px"
              >
                <a-select-option
                  v-for="(item, index) in updateStateList"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="闲鱼状态" name="fishState">
              <a-select
                v-model:value="formState.fishState"
                placeholder="请选择"
                allowClear
                style="width: 250px"
              >
                <a-select-option
                  v-for="(item, index) in wechatStateList"
                  :key="index"
                  :value="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="备注" name="remark">
              <a-input v-model:value="formState.remark" placeholder="备注" style="width: 250px" />
            </a-form-item>

            <a-form-item style="text-align: right">
              <a-button type="primary" @click="search">搜索</a-button>
              <a-button @click="reset" style="margin-left: 10px">重置</a-button>
            </a-form-item>
          </div>
        </SearchDrawer>

        <!-- <a-form-item style="margin-left: -8px">
          <div
            style="
              display: flex;
              align-items: center;
              color: #1890ff;
              justify-content: center;
              margin-left: 8px;
              cursor: pointer;
            "
            @click="() => (searchFlag = !searchFlag)"
          >
            <div style="margin-top: 2px">{{ searchFlag ? '收起' : '展开' }}</div>
            <UpOutlined
              :style="{
                transform: !searchFlag ? 'rotate(180deg)' : 'rotate(0)',
                transition: '0.5s',
                color: '#1890ff',
                fontSize: '14px',
                marginLeft: '8px',
              }"
            />
          </div>
        </a-form-item> -->

        <a-form-item>
          <a-button type="primary" @click="search">搜索</a-button>
          <a-button @click="reset">重置</a-button>
          <a-button type="primary" @click="advancedSearch">高级搜索</a-button>
        </a-form-item>
      </a-form>
    </div>

    <div style="margin: 5px 0">
      <a-button type="primary" @click="showGroupList">分组管理</a-button>

      <a-button type="primary" style="margin: 0 10px" @click="showIMAuthorization">开通IM权限</a-button>
      <a-button type="primary" @click="addAccount">添加账号</a-button>

      <!-- <a-button type="primary" style="border-radius: 6px; margin-left: 10px" @click="addGroup">
        设置分组
      </a-button> -->

      <a-dropdown v-if="selectedRowKey.length > 0">
        <a-button style="margin-left: 10px;">
          批量操作
          <DownOutlined />
        </a-button>
        <template #overlay>
          <a-menu>
            <a-menu-item @click="addGroup">设置分组</a-menu-item>
          </a-menu>
        </template>
      </a-dropdown>
    </div>
    <a-alert
      description="小提示：只要鼠标在表格上，按住左Shift键并滚动鼠标滚轮就可以横向滚动表格"
      type="info"
      banner
      style="margin-bottom: 10px; padding: 10px"
    />
    <a-table
      style="overflow-x: scroll"
      :columns="columns"
      :data-source="dataSource"
      :pagination="pagination"
      :loading="loading"
      @change="changePage"
      rowKey="id"
      :row-selection="{ selectedRowKeys: selectedRowKey, onChange: onSelectChange }"
      :scroll="{ x: 100 }"
      size="small"
    >
      <template #emptyText>
        <a-empty description="暂无数据" />
      </template>

      <template #headerCell="{ column }">
        <template v-if="column.key === 'id'">
          <span>id</span>
        </template>
        <template v-if="column.key === 'action'">
          <div>操作</div>
        </template>
        <template v-if="column.key === 'avatar'">
          <div style="text-align: center">
            <span>头像</span>
          </div>
        </template>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'xyAccount'">
          <a-descriptions bordered size="small" :column="1">
            <a-descriptions-item label="昵称">{{ record.nickName }}</a-descriptions-item>
            <a-descriptions-item label="分组">
              {{ showGroupName(record.groupId) }}
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-else-if="column.key === 'shopLevel'">
          <a-descriptions bordered size="small" :column="1">
            <a-descriptions-item label="评价分：">{{ record.shopScore }}</a-descriptions-item>
            <a-descriptions-item label="好评率：">
              {{ record.shopPraiseRatio }}%
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-else-if="column.key === 'avatar'">
          <div class="imgBox" v-if="record.avatar != ''">
            <img :src="record.avatar" alt="" />
          </div>
          <div class="imgBox" v-else>
            <img src="~@/assets/xyImg.png" />
          </div>
        </template>

        <template v-else-if="column.key === 'createTime'">
          <a-descriptions bordered size="small" :column="1">
            <a-descriptions-item label="创建时间">
              {{ timeFormat(record.createTime) }}
            </a-descriptions-item>
            <a-descriptions-item label="过期时间">
              {{ timeFormat(record.expireTime) }}
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-else-if="column.key === 'groupId'">
          <a-descriptions bordered size="small" :column="1">
            <a-descriptions-item label="编号">
              <div style="width: 200px">{{ record.id }}</div>
            </a-descriptions-item>
            <a-descriptions-item label="备注">
              <div style="display: flex; align-items: center">
                <a-tooltip placement="top" v-if="!record.isRemarkShow">
                  <template #title>
                    <span>{{ record.remark }}</span>
                  </template>
                  <div class="hiddenText">{{ record.remark }}</div>
                </a-tooltip>

                <a-input
                  v-else
                  v-model:value="record.remark"
                  @blur="handleRemark(record.id, record.remark)"
                  style="border: 0"
                />
                <EditOutlined
                  @click="EditRemarkSet(record)"
                  v-if="!record.isRemarkShow"
                  style="margin-left: 6px; color: #1890ff"
                />
              </div>
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-else-if="column.key === 'xyAuthorization'">
          <a-descriptions bordered size="small" :column="1">
            <a-descriptions-item label="闲鱼授权">
              <a-tag color="blue" v-if="getAuthoration(record.authExpireTime) == 1">
                已授权({{ timeFormat(record.authExpireTime) }})
              </a-tag>
              <a-tag color="red" v-if="getAuthoration(record.authExpireTime) == -1">未授权</a-tag>
              <a-tag color="red" v-if="getAuthoration(record.authExpireTime) == -2">授权过期</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="续费状态">
              <a-tag color="blue" v-if="new Date().getTime() < record.expireTime">无需续费</a-tag>
              <a-tag color="red" v-else>需要续费</a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-else-if="column.key === 'userName'">
          <a-descriptions bordered size="small" :column="1">
            <a-descriptions-item label="鱼小铺等级">
              <div v-if="record.shopLevel">
                <span style="color: #00e000">Lv{{ record.shopLevel }}</span>
                （差
                <span style="color: ">{{ record.shopNextLevelScore }}</span>
                分升级）
              </div>
              <div v-else>未开通</div>
            </a-descriptions-item>
            <a-descriptions-item label="会员名">{{ record.memberName }}</a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-else-if="column.key === 'fishState'">
          <a-descriptions bordered size="small" :column="1">
            <a-descriptions-item label="闲鱼状态">
              <a-tag color="blue" v-if="record.fishState == 1">正常</a-tag>
              <a-tag color="red" v-else>离线</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="客户端状态">
              <a-tag color="blue" v-if="record.robotState == 1">正常</a-tag>
              <a-tag color="red" v-else-if="record.robotState == -1">异常</a-tag>
              <a-tag color="red" v-else>手动关闭</a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </template>

        <template v-else-if="column.key === 'updateState'">
          <div style="width: 80px; text-align: center">
            <a-tag color="red" v-if="record.updateState == 1">需要更新</a-tag>
            <a-tag color="blue" v-else>无需更新</a-tag>
          </div>
        </template>

        <template v-else-if="column.key === 'action'">
          <div style="width: 100px; margin: 0; padding: 0">
            <div>
              <a @click="authorization(record.id)">闲鱼授权</a>
            </div>
            <div>
              <a @click="rechargeAuthorization(record.id)">充值时长</a>
            </div>
            <div>
              <a @click="transferDuration(record.id)">转移时长</a>
            </div>
          </div>
        </template>
      </template>
    </a-table>

    <SetGroup ref="setGroupRef" @refresh="getList"></SetGroup>
    <DelWxRobot ref="delWxRobotRef" @refresh="getList"></DelWxRobot>
    <EditRemark ref="editRemarkRef" @refresh="getList"></EditRemark>
    <GroupList ref="groupListRef"></GroupList>
    <RechargeAuthorization
      ref="rechargeAuthorizationRef"
      @refresh="getList"
    ></RechargeAuthorization>
    <Authorization ref="authorizationRef"></Authorization>
    <IMAuthorization ref="IMAuthorizationRef"></IMAuthorization>
    <TransferDuration ref="TransferDurationRef" @refresh="getList"></TransferDuration>
  </div>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 160px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.formClass {
  :nth-child(1) {
    // margin-bottom: 2px;
  }
}

.searchBox {
  // margin-bottom: 10px;
  display: flex;

  input {
    // width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

a:hover {
  color: red;
}

.imgBox {
  width: 50px;
  height: 50px;
  margin: 0 auto;
  border-radius: 50%;
  overflow: hidden;

  img {
    height: 50px;
  }
}

.popoverImg {
  width: 300px;

  img {
    width: 100%;
  }
}

.robitStatusClass {
  text-align: center;
}

:deep(.ant-form-item-label) {
  width: 70px;
}
</style>
